<?php

namespace app\admin\controller\course;

use app\admin\model\course\Order;
use app\common\controller\Backend;
use app\common\model\User;
use think\Db;

/**
 * 转校管理
 *
 * @icon fa fa-circle-o
 */
class Transfer extends Backend
{

    /**
     * Transfer模型对象
     * @var \app\admin\model\course\Transfer
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\course\Transfer;
        $statusList = $this->model->getStatusList();
        $this->view->assign("statusList", $statusList);
        $this->assignconfig("statusList", $statusList);

        $typeList = $this->model->getTypeList();
        $this->view->assign("typeList", $typeList);
        $this->assignconfig("typeList", $typeList);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['student'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('student')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /*
     * 申请
     * */
    public function apply(){

        $ids = $this->request->request("ids");
        $row = $this->model->get($ids);
        $order = new Order();
        $condition = [
            "order.id" => $row['order_id'],
        ];
        $orderInfo = $order->getOrderInfo($condition);
        if ($this->request->isPost()) {
            //拒绝的话
            $apply = $this->request->request("apply");
            $refuse_content = $this->request->request("refuse_content");

            //拒绝
            if($apply == "refuse"){
                $row->refuseApply($refuse_content);
            }else{
                $params = $this->request->post('row/a');
                if (empty($params)) {
                    $this->error(__('Parameter %s can not be empty', ''));
                }
                $params = $this->preExcludeFields($params);


                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $surplus_class_hour = $orderInfo['surplus_class_hour'];

                if($orderInfo['surplus_class_hour'] <= 0){
                    exception("剩余课时不能小于0");
                }
                Db::startTrans();
                try {

                    //先完成当前订单
                    Order::setSuccessStatus($row['order_id']);

                    //重新下单
                    $user = User::get($params['user_id']);
                    if(empty($params['config'])){
                        exception("请选择班次");
                    }
                    $time_arr = json_decode($params['config'],true);
                    if(count($time_arr) == 0 ){
                        exception("请选择班次");
                    }
//            dump($params);
//            dump($time_arr);
//            exit;
                    $orderModel = new Order();
                    $params['type'] = $orderModel::TYPE_TRANSFER;
                    $params['pay_type'] = $orderModel::TYPE_TRANSFER;


                    $params['parent_name'] = $orderInfo['parent_name'];
                    $params['phone_1'] = $orderInfo['phone_1'];
                    $params['phone_2'] = $orderInfo['phone_2'];
                    $params['phone_3'] = $orderInfo['phone_3'];
                    foreach ($time_arr as $key => $value){
                        $params['school_id'] = $value['school_id'];
                        $params['classes_id'] = $value['classes_id'];
                    }
                    $admin_msg = $this->auth->nickname."转单创建";


//                dump($params);exit;
                    $orderId = $orderModel->createOrder($user, $params,$time_arr,0,$admin_msg);


                    $newOrder = $orderModel->where("id", $orderId['order_id'])
                        ->find();

                    $newOrder->payOrder($user, "admin", "admin");


//                dump($surplus_class_hour);exit;
                    //消耗课时
                    $deal_class_hour = $newOrder['class_hour'] - $surplus_class_hour;
//                dump($newOrder['class_hour']);
//                dump($deal_class_hour);
//                exit;
                    if($deal_class_hour != 0){
                        if($deal_class_hour > 0){
                            $msg = $this->auth->nickname . "转单,设置剩余课时：{$surplus_class_hour}";
                            $newOrder->useHour($msg, $deal_class_hour);
                        }else{
                            exception("当前课程总课时为：{$newOrder['class_hour']},请检查剩余课程配置");
                        }
                    }


                    $newOrderInfo = $order->getOrderInfo(["order.id" => $newOrder['id']]);
                    $row->successApply($orderInfo,$newOrderInfo);

                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }


            $this->success("设置成功");
        }

        if (!$row) {
            $this->error(__('No Results were found'));
        }


        $this->view->assign('orderInfo', $orderInfo);
        $this->view->assign('row', $row);
        $this->assignconfig('row', $row);
        return $this->view->fetch();
    }
}
